﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace ScratchCard.AppCode
{
    public class LockBoxex
    {
        private static object _lock = new object();

        private static string file = "prize.json";
        private static string _appPath = System.AppDomain.CurrentDomain.BaseDirectory;
        private string setttingPath = Path.Combine(_appPath, "PrizeSettingex");

        private static LockBoxex _instance;
        public static LockBoxex Instance
        {
            get
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new LockBoxex();
                    }
                }

                return _instance;
            }
        }

        private string _interpretation = "本活动最终解释权归酷居科技所有";

        private int _validTimes = 1;

        private List<AwardModel> _awards = new List<AwardModel>
        {
            new AwardModel()
            {
                PrizeLevel = Prize.First,
                Prize = "一等奖",
                Description = "一等奖：智能家居套装",
                Price = "价值2888元",
                Count = 0,
                Random = 0.001f,
            },
            new AwardModel()
            {
                PrizeLevel = Prize.Second,
                Prize = "二等奖",
                Description = "二等奖：充电宝",
                Price = "价值250元",
                Count = 0,
                Random = 0.002f,
            },
            new AwardModel()
            {
                PrizeLevel = Prize.Third,
                Prize = "三等奖",
                Description = "三等奖：迷你充电器",
                Price = "价值100元",
                Count = 0,
                Random = 0.02f,
            },
            new AwardModel()
            {
                PrizeLevel = Prize.Forth,
                Prize = "四等奖",
                Description = "四等奖：迷你USB高速数据线",
                Price = "价值38元",
                Count = 0,
                Random = 0.2f,
            },
        };
        private List<string> _introductions = new List<string> {
              "亲，酷居刮奖区中有乾坤，祝您好运！",
                "活动地点：深圳会展中心4号馆C111-115",
                "活动时间：2015.06.26-06.27"
        };

        private LockBoxex()
        {
            if (!Directory.Exists(setttingPath))
            {
                Directory.CreateDirectory(setttingPath);
            }

            var filename = Path.Combine(setttingPath, file);

            if (File.Exists(filename))
            {
                var json = File.ReadAllText(filename, System.Text.Encoding.GetEncoding("utf-8"));

                var o = new
                {
                    ValidTimes,
                    Interpretation ,
                    Introductions =new List<string>(),
                    Awards = new List<AwardModel>(),
                };
                var model = JsonHelper.DeserializeJsonToObject(json,o.GetType());
                if (model != null)
                {
                    _validTimes = model.ValidTimes;
                    _interpretation = model.Interpretation;
                    _introductions = model.Introductions;

                    for (int i = 0; i < _awards.Count; i++)
                    {
                        var award = _awards[i];
                        var list = (List<AwardModel>)model.Awards;

                        if (i < list.Count)
                        {
                            var first = list[i];
                            if (first != null)
                            {
                                award.Count = first.Count;
                                award.IssueCount = first.IssueCount;
                                award.Description = first.Description;
                                award.Price = first.Price;
                                award.Prize = first.Prize;
                                award.PrizeLevel = first.PrizeLevel;
                                award.Random = first.Random;
                            }
                        }
                    }
                }
            }
        }

        internal void SaveSetting(int validTimes, string interpretation, string introductions, string awards)
        {
            lock (_lock)
            {
                _validTimes = validTimes;
                _interpretation = interpretation;
                _introductions = new List<string>(introductions.Split(','));
                var models = JsonHelper.DeserializeJsonToList<AwardModel>(awards);

                for (int i = 0; i < _awards.Count; i++)
                {
                    var item = _awards[i];
                    if (i < models.Count)
                    {
                        var model = models[i];
                        if (model != null)
                        {
                            item.PrizeLevel = model.PrizeLevel;
                            item.Prize = model.Prize;
                            item.IssueCount = model.IssueCount;
                            item.Count = model.Count;
                            item.Description = model.Description;
                            item.Price = model.Price;
                            item.Random = model.Random;
                        }
                    }
                }

                if (!Directory.Exists(setttingPath))
                {
                    Directory.CreateDirectory(setttingPath);
                }

                var filename = Path.Combine(setttingPath, file);

                var json = JsonHelper.SerializeObject(new
                {
                    ValidTimes = ValidTimes,
                    Interpretation = Interpretation,
                    Introductions = Introductions,
                    Awards = Awards,
                });

                File.WriteAllText(filename, json, System.Text.Encoding.GetEncoding("utf-8"));
            }
        }

        internal string GetSetting()
        {
            return JsonHelper.SerializeObject(new {
                Interpretation = Interpretation,
                Introductions = Introductions,
                Awards = Awards,
                ValidTimes = ValidTimes,
            });
        }

        public string GetSettingOrderbyPrizeLevel()
        {
            return JsonHelper.SerializeObject(new
            {
                Interpretation = Interpretation,
                Introductions = Introductions,
                Awards = Awards.OrderBy(o => o.PrizeLevel),
                ValidTimes = ValidTimes,
            });
        }

        public List<AwardModel> Awards
        {
            get { return _awards; }
        }

        /// <summary>
        /// 每个设备的在活动期间可抽奖次数
        /// </summary>
        public int ValidTimes { get { return _validTimes; } set { _validTimes = value; } }

        public List<string> Introductions { get { return _introductions; } }

        public string Interpretation { get { return _interpretation; } set { _interpretation = value; } }

        /// <summary>
        /// 抽奖函数
        /// </summary>
        /// <param name="validTimes">有效次数小于1 的时候，是可抽取的。</param>
        /// <returns></returns>
        public Prize WinLottery(int validTimes)
        {
            lock (_lock)
            {
                if (validTimes < _validTimes || _validTimes <=0)
                {
                    byte[] buffer = Guid.NewGuid().ToByteArray();
                    int iSeed = BitConverter.ToInt32(buffer, 0);
                    var random = new Random(iSeed); //随机数

                    var value = random.NextDouble();

                    foreach (var award in _awards.OrderBy(o => o.Random))
                    {
                        if (value < award.Random && award.IssueCount < award.Count)
                        {
                            award.IssueCount++;
                            return award.PrizeLevel;
                        }
                    }
                }
                else
                {
                    return Prize.NoLucky;
                }
            }

            return Prize.ThankYou;
        }

        public enum Prize
        {
            Grand = 0,
            First = 1,
            Second = 2,
            Third = 3,
            Forth = 4,
            Fifth = 5,
            ThankYou = 10,
            NoLucky = 11,
        }

        public string GetIssueCount()
        {
            return JsonHelper.SerializeObject(_awards.Select(o => new { o.PrizeLevel, o.IssueCount }));
        }

    }
}